import { useNavigate, useLocation, useSearchParams, useParams } from "react-router-dom";
import {createContext, useContext, useRef, useEffect, useState} from "react";
 
// 创建Context
const RouterContext = createContext();
 
// RouteHistoryProvider组件
export const RouteHistoryProvider = ({ children }) => {
  const maxHistory = 10;
  const [history, setHistory] = useState([]);
  const location = useLocation();
  const lastLocationRef = useRef(null);
 
  useEffect(() => {
    // 检查位置是否真正改变（这里简单比较pathname，您可以根据需要添加更多条件）
    if (lastLocationRef.current === null || location.pathname !== lastLocationRef.current.pathname) {
      if (history.length >= maxHistory) {
        setHistory([...history.slice(1), location]);
      } else {
        setHistory([...history, location]);
      }
    }
    // 更新引用
    lastLocationRef.current = location;
  }, [location, history]);
 
  return (
    <RouterContext.Provider value={history}>
      {children}
    </RouterContext.Provider>
  );
}

export const withRouterContext = (Component) => {
  return (props) => {
    const navigate = useNavigate();
    const searchParams = useSearchParams();
    const routerParams = useParams();
    const history = useContext(RouterContext);
 
    // 获取最后一个位置（可以封装成辅助函数）
    const lastLocation = history[history.length - 1] || null;
 
    return (
      <Component
        {...props}
        navigate={navigate}
        location={lastLocation} // 传递最后一个位置
        searchParams={searchParams}
        routerParams={routerParams}
        history={history}
      />
    );
  };
}